package com.cmcc.pp.ui.transactiondata;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cmcc.pp.R;
import com.cmcc.pp.base.BFragment;
import com.cmcc.pp.entity.transactiondata.BusinessDev;
import com.cmcc.pp.entity.transactiondata.CommonItem;
import com.cmcc.pp.entity.transactiondata.RepairOrder;
import com.cmcc.pp.ui.MianActivityDrawerLayout;
import com.cmcc.pp.ui.transactiondata.adapter.BusinessDevAdapter;
import com.cmcc.pp.ui.transactiondata.adapter.CommonAdapter;
import com.cmcc.pp.ui.transactiondata.adapter.RepairOrderAdapter;
import com.cmcc.pp.ui.widget.FillLineChart;
import com.cmcc.pp.ui.widget.PieView;
import com.cmcc.pp.ui.widget.RefreshLinearLayout;
import com.cmcc.pp.ui.widget.TabLayout;
import com.cmcc.pp.util.UIUtils;
import com.zrspring.libv2.util.ToastUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by ABC on 2017/12/12.
 * 业务数据
 */

public class FragmentTransactionFragment extends BFragment {

    @Bind(R.id.content)
    RefreshLinearLayout refreshLinearLayout;
    @Bind(R.id.fragmentTransactionData_pieData)
    PieView pieView;
    @Bind(R.id.fragmentTransactionData_rvBusinessData)
    RecyclerView rvBusinessData;
    @Bind(R.id.fragmentTransactionData_rvBindings)
    RecyclerView rvBindings;
    @Bind(R.id.fragmentTransactionData_rvGatewayData)
    RecyclerView rvGatewayData;
    @Bind(R.id.fragmentTransactionData_fillLineChart)
    FillLineChart fillLineChart;
    @Bind(R.id.fragmentTransactionData_elvRepairOrder)
    ExpandableListView elvRepairOrder;
    @Bind(R.id.fragmentTransactionData_tvLocation)
    TextView tvLocation;
    @Bind(R.id.fragmentTransactionData_trendTab)
    TabLayout trendTab;

    @Bind(R.id.scrollView)
    ScrollView scrollView;

    private boolean flag;

    private final int[] bindImgResIds = {R.mipmap.icon_bind_end, R.mipmap.icon_bind_ratio, R.mipmap.icon_bind_user};
    private final int[] gatewayImgResIds = {R.mipmap.icon_gateway_total, R.mipmap.icon_gateway_store
            , R.mipmap.icon_gateway_putpack, R.mipmap.icon_gateway_newadd};
    private final int[] repairOderImgResIds = {R.mipmap.icon_broad_band, R.mipmap.icon_audio
            , R.mipmap.icon_ott, R.mipmap.icon_other};

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    refreshLinearLayout.updateStatus(RefreshLinearLayout.Companion.getFAIL(), null, false);
                    refreshLinearLayout.updateStatus(RefreshLinearLayout.Companion.getFAIL());
                    break;
                case 2:
                    refreshLinearLayout.updateStatus(RefreshLinearLayout.Companion.getSUCCESS());
                    break;
                case 3:
                    if (flag) {
                        refreshLinearLayout.updateStatus(RefreshLinearLayout.Companion.getLOADING());
                        handler.sendEmptyMessageDelayed(2, 5000);
                    } else {
                        refreshLinearLayout.updateStatus(RefreshLinearLayout.Companion.getLOADING());
                        handler.sendEmptyMessageDelayed(1, 5000);
                    }
                    break;
            }
        }
    };

    @Override
    protected boolean getHasTitle() {
        return true;
    }

    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_transactiondate;
    }

    @Override
    public void initView(View fragmentView) {
        getHeader().setTitle(R.string.str_transactiondata);
        getHeader().showLeftImage(R.mipmap.iocn_menubar);
        getHeader().showRightImage(R.mipmap.icon_share);

        tvLocation.setText("安徽省");

        flag = false;

        refreshLinearLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshLinearLayout.packUpHeader();
            }
        });

        Message message = Message.obtain();
        message.what = 3;
        handler.sendMessage(message);

        drawPieChart();
        drawLineChart();

        fillLineChart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = !flag;
                handler.sendEmptyMessage(3);
            }
        });

        rvBindings.setLayoutManager(new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false));
        rvBusinessData.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rvGatewayData.setLayoutManager(new GridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false));
    }

    private void drawLineChart() {
        ArrayList<FillLineChart.DataPoint> dataPoints = new ArrayList<>();
        FillLineChart.DataPoint dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-10");
        dataPoint.setYValue(3800f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-11");
        dataPoint.setYValue(1000f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-12");
        dataPoint.setYValue(2200f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-13");
        dataPoint.setYValue(3300f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-14");
        dataPoint.setYValue(3500f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-15");
        dataPoint.setYValue(3500f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-16");
        dataPoint.setYValue(2300f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-17");
        dataPoint.setYValue(4500f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-18");
        dataPoint.setYValue(3500f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-19");
        dataPoint.setYValue(2500f);
        dataPoints.add(dataPoint);
        dataPoint = new FillLineChart.DataPoint();
        dataPoint.setXDate("11-20");
        dataPoint.setYValue(3500f);
        dataPoints.add(dataPoint);
        fillLineChart.setData(dataPoints);
    }

    private void drawPieChart() {
        ArrayList<HashMap<String, Object>> datas = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "其他");
        map.put("ratio", 0.05f);
        map.put("type", PieView.Companion.getOTHER());
        map.put("value", 100.00);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "OTT");
        map.put("ratio", 0.10f);
        map.put("type", PieView.Companion.getOTT());
        map.put("value", 1200);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "OTT");
        map.put("ratio", 0.05f);
        map.put("type", PieView.Companion.getOTT());
        map.put("value", 1200);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "OTT");
        map.put("ratio", 0.05f);
        map.put("type", PieView.Companion.getOTT());
        map.put("value", 1200);
        datas.add(map);

        map = new HashMap<>();
        map.put("name", "OTT");
        map.put("ratio", 0.25f);
        map.put("type", PieView.Companion.getOTT());
        map.put("value", 1200);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "宽带");
        map.put("ratio", 0.2f);
        map.put("type", PieView.Companion.getBROAD_BAND());
        map.put("value", 30.00);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "语音");
        map.put("ratio", 0.1f);
        map.put("type", PieView.Companion.getAUDIO());
        map.put("value", 15.000);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "语音");
        map.put("ratio", 0.1f);
        map.put("type", PieView.Companion.getAUDIO());
        map.put("value", 15.000);
        datas.add(map);
        map = new HashMap<>();
        map.put("name", "语音");
        map.put("ratio", 0.1f);
        map.put("type", PieView.Companion.getAUDIO());
        map.put("value", 15.000);
        datas.add(map);
        pieView.setData(datas);
    }


    @Override
    public void loadData() {

        initGateway();
        initBinds();
        initBusinessDev();
        initRepairOrder();

        trendTab.setOnCheckChangeListener(new TabLayout.OnTabCheckedChangeListener() {
            @Override
            public void onCheckedChanged(@NotNull RadioGroup group, int checkedId) {
                if (checkedId == R.id.layoutTab_left) {
                    ToastUtils.show("点击了左边");
                } else {
                    ToastUtils.show("点击了右边");
                    drawFace();
                }
            }
        });


    }

    private void drawFace() {
        int h = 0;
        RefreshLinearLayout view = (RefreshLinearLayout) scrollView.getChildAt(0);
        for (int i = 0; i < view.getChildCount(); i++) {
            h += view.getChildAt(i).getHeight();
        }

        final Bitmap bitmap = Bitmap.createBitmap(getActivity().getResources().getDisplayMetrics().widthPixels
                , h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);

        Observable.just(true).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                FileOutputStream fileOutputStream = new FileOutputStream(UIUtils.getCachePath() + File.separator + "bitmap.jpg");
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                bitmap.recycle();
            }
        }, new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                System.out.println("=========================失败-----------------------");
            }
        });
    }

    private void initRepairOrder() {
        elvRepairOrder.setGroupIndicator(null);

        ArrayList<RepairOrder> repairOrders = new ArrayList<>();

        RepairOrder repairOrder = new RepairOrder();
        repairOrder.parentImgResId = repairOderImgResIds[0];
        repairOrder.itemName = "宽带";
        repairOrder.children = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            RepairOrder.RepairOderChild repairOderChild = new RepairOrder.RepairOderChild();
            repairOderChild.childItemName = "新装" + i;
            repairOderChild.childItemValue = "5000" + i;
            repairOrder.children.add(repairOderChild);
        }
        repairOrders.add(repairOrder);

        repairOrder = new RepairOrder();
        repairOrder.parentImgResId = repairOderImgResIds[1];
        repairOrder.itemName = "语音";
        repairOrder.children = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            RepairOrder.RepairOderChild repairOderChild = new RepairOrder.RepairOderChild();
            repairOderChild.childItemName = "新装" + i;
            repairOderChild.childItemValue = "5000" + i;
            repairOrder.children.add(repairOderChild);
        }
        repairOrders.add(repairOrder);

        repairOrder = new RepairOrder();
        repairOrder.parentImgResId = repairOderImgResIds[2];
        repairOrder.itemName = "OTT";
        repairOrder.children = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            RepairOrder.RepairOderChild repairOderChild = new RepairOrder.RepairOderChild();
            repairOderChild.childItemName = "新装" + i;
            repairOderChild.childItemValue = "5000" + i;
            repairOrder.children.add(repairOderChild);
        }
        repairOrders.add(repairOrder);

        repairOrder = new RepairOrder();
        repairOrder.parentImgResId = repairOderImgResIds[3];
        repairOrder.itemName = "其他";
        repairOrder.children = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            RepairOrder.RepairOderChild repairOderChild = new RepairOrder.RepairOderChild();
            repairOderChild.childItemName = "新装" + i;
            repairOderChild.childItemValue = "5000" + i;
            repairOrder.children.add(repairOderChild);
        }
        repairOrders.add(repairOrder);

        final RepairOrderAdapter repairOrderAdapter = new RepairOrderAdapter(getContext(), repairOrders);
        elvRepairOrder.setAdapter(repairOrderAdapter);
//        elvRepairOrder.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                addAnimToView(parent, v, groupPosition);
//                return false;
//            }
//        });
        elvRepairOrder.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                int count = elvRepairOrder.getExpandableListAdapter().getGroupCount();
                for(int j = 0; j < count; j++){
                    if(j != groupPosition){
                        elvRepairOrder.collapseGroup(j);
                    }
                }
            }
        });

        if (repairOrders.size() > 0) {
            elvRepairOrder.expandGroup(0);
        }
    }

    private void addAnimToView(ExpandableListView parent, View v, int groupPosition) {
        ImageView ivArrow = v.findViewById(R.id.itemRepairParent_imageRight);
        if (parent.isGroupExpanded(groupPosition)) {

            RotateAnimation anim = new RotateAnimation(90, 0, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(200);
            anim.setFillAfter(true);
            anim.setAnimationListener(getAnimListener(v));
            ivArrow.startAnimation(anim);
        } else {
            RotateAnimation anim = new RotateAnimation(0, 90, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(200);
            anim.setFillAfter(true);
            anim.setAnimationListener(getAnimListener(v));
            ivArrow.startAnimation(anim);
        }
    }

    private void initBusinessDev() {
        ArrayList<BusinessDev> businessDevs = new ArrayList<>();

        BusinessDev businessDev = new BusinessDev();
        businessDev.companyName = "厂家A";
        businessDev.inventory = "6000";
        businessDev.inventoryRatio = 1.0f;
        businessDev.putPack = "4000";
        businessDev.putPackRatio = 0.6f;
        businessDevs.add(businessDev);

        businessDev = new BusinessDev();
        businessDev.companyName = "厂家B";
        businessDev.inventory = "5400";
        businessDev.inventoryRatio = 0.75f;
        businessDev.putPack = "3800";
        businessDev.putPackRatio = 0.45f;
        businessDevs.add(businessDev);

        businessDev = new BusinessDev();
        businessDev.companyName = "厂家C";
        businessDev.inventory = "440";
        businessDev.inventoryRatio = 0.2f;
        businessDev.putPack = "2200";
        businessDev.putPackRatio = 0.35f;
        businessDevs.add(businessDev);

        businessDev = new BusinessDev();
        businessDev.companyName = "厂家D";
        businessDev.inventory = "5000";
        businessDev.inventoryRatio = 0.75f;
        businessDev.putPack = "2200";
        businessDev.putPackRatio = 0.35f;
        businessDevs.add(businessDev);

        BusinessDevAdapter businessDevAdapter = new BusinessDevAdapter(businessDevs);
        rvBusinessData.setAdapter(businessDevAdapter);
    }

    private void initGateway() {
        ArrayList<CommonItem> commonItems = new ArrayList<>();
        CommonItem commonItem = new CommonItem();
        commonItem.bottomText = "入库总量";
        commonItem.centerText = "8.000";
        commonItem.imgResId = gatewayImgResIds[0];
        commonItems.add(commonItem);

        commonItem = new CommonItem();
        commonItem.bottomText = "库存量";
        commonItem.centerText = "5.000";
        commonItem.imgResId = gatewayImgResIds[1];
        commonItems.add(commonItem);

        commonItem = new CommonItem();
        commonItem.bottomText = "放装量";
        commonItem.centerText = "3.000";
        commonItem.imgResId = gatewayImgResIds[2];
        commonItems.add(commonItem);

        commonItem = new CommonItem();
        commonItem.bottomText = "昨日新增";
        commonItem.centerText = "3000";
        commonItem.imgResId = gatewayImgResIds[3];
        commonItems.add(commonItem);

        CommonAdapter commonAdapter = new CommonAdapter(commonItems);
        commonAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        rvGatewayData.setAdapter(commonAdapter);
    }

    private void initBinds() {
        ArrayList<CommonItem> commonItems = new ArrayList<>();
        CommonItem commonItem = new CommonItem();
        commonItem.bottomText = "绑定用户量";
        commonItem.centerText = "4.000";
        commonItem.imgResId = bindImgResIds[0];
        commonItems.add(commonItem);

        commonItem = new CommonItem();
        commonItem.bottomText = "绑定终端";
        commonItem.centerText = "22.6";
        commonItem.imgResId = bindImgResIds[1];
        commonItems.add(commonItem);
        commonItem = new CommonItem();

        commonItem.bottomText = "绑定率";
        commonItem.centerText = "100%";
        commonItem.imgResId = bindImgResIds[2];
        commonItems.add(commonItem);

        CommonAdapter commonAdapter = new CommonAdapter(commonItems);
        commonAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        rvBindings.setAdapter(commonAdapter);
    }

    private Animation.AnimationListener getAnimListener(final View view) {
        Animation.AnimationListener listener = new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                view.setEnabled(false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setEnabled(true);
                view.findViewById(R.id.itemRepairParent_imageRight).clearAnimation();
            }
        };
        return listener;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void onLeftClick() {
        MianActivityDrawerLayout mianActivityDrawerLayout = (MianActivityDrawerLayout) getActivity();
        mianActivityDrawerLayout.closemenu();
    }
}
